﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using DotVVM.Framework.ViewModel;
using DotVVM.Framework.Runtime.Filters;
using VOICeVIO.Hybrid.Models;
using VOICeVIO.Hybrid.Services;


namespace VOICeVIO.Hybrid.ViewModels.CRUD
{
    public class DetailViewModel : MasterPageViewModel
    {
        public bool CanDownload { get; set; } = true;
        private readonly HybridService _hybridService;
        private readonly SvssService _cevioService;

        public DetailViewModel(HybridService hybridService)
        {
            this._hybridService = hybridService;
        }

        public SongDetailModel Song { get; set; }

        public override async Task PreRender()
        {
            if (!int.TryParse(Context.Parameters["Id"].ToString(), out var id))
            {
                return;
            }
            Song = await _hybridService.GetSongByIdAsync(id);
            await base.PreRender();
        }

        public async Task DownloadSong()
        {
            var uid = Song.Uid;
            if (string.IsNullOrEmpty(Song.Uid))
            {
                var song = await _hybridService.GetSongByIdAsync(Song.Id);
                if (song == null)
                {
                    CanDownload = false;
                    return;
                }

                uid = song.Uid;
            }

            var fs = _cevioService.GetWave(Guid.Parse(uid));
            if (fs == null)
            {
                CanDownload = false;
                return;
            }

            CanDownload = true;
            Context.ReturnFile(fs, Song.SongName + ".wav", "audio/x-wav");
        }
    }
}
